package com.xzh.api;

import com.xzh.model.Reviews;
import com.xzh.model.search.ReviewDao;
import com.xzh.service.ReviewsService;
import com.xzh.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/reviews")
public class ReviewsApi {
    private ReviewsService reviewsService;

    @Autowired
    public void setReviewsService(ReviewsService reviewsService) {
        this.reviewsService = reviewsService;
    }

    @GetMapping
    public ResponseEntity<JsonResult<?>> selectAll() {
        List<Reviews> reviews = reviewsService.selectList();
        return ResponseEntity.ok(JsonResult.success(reviews));
    }

    @PostMapping
    public ResponseEntity<JsonResult<?>> add(@RequestBody Reviews reviews) {
        boolean result = reviewsService.save(reviews);
        if (result) {
            return ResponseEntity.ok(JsonResult.success());
        } else {
            return ResponseEntity.ok(JsonResult.fail("添加失败"));
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<JsonResult<?>> delete(@PathVariable("id") Integer id) {
        boolean result = reviewsService.removeById(id);
        if (result) {
            return ResponseEntity.ok(JsonResult.success());
        } else {
            return ResponseEntity.ok(JsonResult.fail("删除失败"));
        }
    }

    @PutMapping
    public ResponseEntity<JsonResult<?>> update(@RequestBody Reviews reviews) {
        int count = reviewsService.updateById(reviews);
        if (count > 0) {
            return ResponseEntity.ok(JsonResult.success());
        } else {
            return ResponseEntity.ok(JsonResult.fail("更新失败"));
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<JsonResult<?>> selectById(@PathVariable("id") Integer id) {
        Reviews reviews = reviewsService.selectById(id);
        return ResponseEntity.ok(JsonResult.success(reviews));
    }

    @PostMapping("/list")
    public ResponseEntity<JsonResult<?>> saveList(@RequestBody ReviewDao reviewDao) {
        boolean result = reviewsService.saveList(reviewDao);
        if (result) {
            return ResponseEntity.ok(JsonResult.success());
        } else {
            return ResponseEntity.ok(JsonResult.fail("添加失败"));
        }
    }

    @GetMapping("/statistics")
    public ResponseEntity<JsonResult<?>> statistics() {
        List<Map<String, Object>> statistics = reviewsService.statistics();
        return ResponseEntity.ok(JsonResult.success(statistics));
    }
}
